from typing import Any, Text, Dict, List
from datetime import datetime, timedelta
import json
from rasa_sdk import Action, Tracker
from rasa_sdk.events import SlotSet
from rasa_sdk.executor import CollectingDispatcher
from rasa_sdk.forms import FormValidationAction
from rasa_sdk.events import AllSlotsReset


class ValidateDynamicForm(FormValidationAction):
    def name(self) -> Text:
        return "validate_dynamic_form"

    async def required_slots(
        self,
        domain_slots: List[Text],
        dispatcher: "CollectingDispatcher",
        tracker: "Tracker",
        domain: "DomainDict",
    ) -> List[Text]:
        # 获取当前场景（例如通过知识库或上下文）
        current_scenario = tracker.get_slot("current_scenario")

        # 根据场景返回需要收集的插槽
        if current_scenario == "ShowMessageAgent":
            return ["show_message_content", "show_message_type"]
        elif current_scenario == "WinOpenAgent":
            return ["win_open_input_type", "win_open_url"]
        elif current_scenario in ["InitAgent", "ActivityAgent"]:
            return ["activity_signal_code", "activity_id", "activity_cube_id"]
        elif current_scenario == "SleepAgent":
            return ["delay_time"]
        elif current_scenario == "SetStateAgent":
            return ["page_state_key", "page_state_default_value", "page_state_default_value_is_object"]
        else:
            return []

class DetermineScenarioAction(Action):
    def name(self) -> Text:
        return "action_determine_scenario"

    def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        # 假设通过用户输入或上下文获取场景类型（这里简化逻辑）
        user_message = tracker.latest_message.get("text")

        # autogen告诉Rasa应该使用哪一个Agent
        scenario = user_message
        # 设置当前场景到插槽
        return [SlotSet("current_scenario", scenario)]

class ActionFrontCodeFormSubmit(Action):
    def name(self) -> Text:
        return "action_front_code_form_submit"

    def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        component = tracker.get_slot("component")
        action = tracker.get_slot("action")
        data = {
            "component": component,
            "action": action,
        }
        message = "词槽填充完毕,数据为：" + json.dumps(data,ensure_ascii=False)
        dispatcher.utter_message(text=message)

        return []


class ActionShowMessageFormSubmit(Action):
    def name(self) -> Text:
        return "action_show_message_form_submit"

    def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        component = tracker.get_slot("component")
        action = tracker.get_slot("action")
        show_message_content = tracker.get_slot("show_message_content")
        show_message_type = tracker.get_slot("show_message_type")
        data = {
            "component": component,
            "action": action,
            "show_message_content": show_message_content,
            "show_message_type": show_message_type,
        }
        message = "词槽填充完毕,数据为：" + json.dumps(data, ensure_ascii=False)
        dispatcher.utter_message(text=message)

        return []


class ActionWinOpenFormSubmit(Action):
    def name(self) -> Text:
        return "action_win_open_form_submit"

    def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        component = tracker.get_slot("component")
        action = tracker.get_slot("action")
        win_open_input_type = tracker.get_slot("win_open_input_type")
        win_open_url = tracker.get_slot("win_open_url")
        data = {
            "component": component,
            "action": action,
            "win_open_input_type": win_open_input_type,
            "win_open_url": win_open_url,
        }
        message = "词槽填充完毕,数据为：" + json.dumps(data, ensure_ascii=False)
        dispatcher.utter_message(text=message)

        return []


class ActionActivityFormSubmit(Action):
    def name(self) -> Text:
        return "action_activity_form_submit"

    def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        component = tracker.get_slot("component")
        action = tracker.get_slot("action")
        activity_signal_code = tracker.get_slot("activity_signal_code")
        activity_id = tracker.get_slot("activity_id")
        activity_cube_id = tracker.get_slot("activity_cube_id")
        data = {
            "component": component,
            "action": action,
            "activity_signal_code": activity_signal_code,
            "activity_id": activity_id,
            "activity_cube_id": activity_cube_id,
        }
        message = "词槽填充完毕,数据为：" + json.dumps(data, ensure_ascii=False)
        dispatcher.utter_message(text=message)

        return []


class ActionDelayFormSubmit(Action):
    def name(self) -> Text:
        return "action_delay_form_submit"

    def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        component = tracker.get_slot("component")
        action = tracker.get_slot("action")
        delay_time = tracker.get_slot("delay_time")

        data = {
            "component": component,
            "action": action,
            "delay_time": delay_time,
        }
        message = "词槽填充完毕,数据为：" + json.dumps(data, ensure_ascii=False)
        dispatcher.utter_message(text=message)

        return []


class ActionPageStateFormSubmit(Action):
    def name(self) -> Text:
        return "action_page_state_form_submit"

    def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        component = tracker.get_slot("component")
        action = tracker.get_slot("action")
        page_state_key = tracker.get_slot("page_state_key")
        page_state_default_value = tracker.get_slot("page_state_default_value")
        page_state_default_value_is_object = tracker.get_slot("page_state_default_value_is_object")

        data = {
            "component": component,
            "action": action,
            "page_state_key": page_state_key,
            "page_state_default_value": page_state_default_value,
            "page_state_default_value_is_object": page_state_default_value_is_object,
        }
        message = "词槽填充完毕,数据为：" + json.dumps(data, ensure_ascii=False)
        dispatcher.utter_message(text=message)

        return []

class ActionDefaultFormSubmit(Action):
    def name(self) -> Text:
        return "action_default_form_submit"

    def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        component = tracker.get_slot("component")
        action = tracker.get_slot("action")
        data = {
            "component": component,
            "action": action,
        }
        message = "词槽填充完毕,数据为：" + json.dumps(data,ensure_ascii=False)
        dispatcher.utter_message(text=message)

        return []

class ActionResetAllSlots(Action):
    def name(self) -> Text:
        return "action_reset_all_slots"

    def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        # 清空所有插槽
        return [AllSlotsReset()]


class ValidatePageStateForm(FormValidationAction):
    def name(self) -> Text:
        return "validate_page_state_form"

    async def validate_page_state_key(
        self,
        value: Text,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> Dict[Text, Any]:
        # 验证消息类型是否合法
        valid_types = ["success", "warning", "info", "error"]
        if value not in valid_types:
            dispatcher.utter_message(text="请输入有效的消息类型：success/warning/info/error")
            return {"page_state_key": None}
        return {"page_state_key": value}

    async def validate_page_state_default_value(
        self,
        value: Text,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> Dict[Text, Any]:
        # 验证消息类型是否合法
        valid_types = ["success", "warning", "info", "error"]
        if value not in valid_types:
            dispatcher.utter_message(text="请输入有效的消息类型：success/warning/info/error")
            return {"page_state_default_value": None}
        return {"page_state_default_value": value}

    async def validate_page_state_default_value_is_object(
        self,
        value: Text,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> Dict[Text, Any]:
        # 验证消息类型是否合法
        valid_types = ["success", "warning", "info", "error"]
        if value not in valid_types:
            dispatcher.utter_message(text="请输入有效的消息类型：success/warning/info/error")
            return {"page_state_default_value_is_object": None}
        return {"page_state_default_value_is_object": value}